﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using CoreEx.Common.Validation;

namespace CoreEx.Common.Implementation.Validation
{
    /// <summary>
    /// Creates a new <see cref="IValidationRule{T}"/> instance.
    /// </summary>
    [Factory(typeof(IValidationRules<>))]
    public class ValidationRulesFactory : IFactory
    {        
        private readonly IDictionary<Type,object> _ruleSets = new Dictionary<Type, object>();

        /// <summary>
        /// Creates a new <see cref="IValidationRule{T}"/> instance 
        /// </summary>
        /// <remarks>
        /// The factory creates singelton instances.
        /// </remarks>
        /// <param name="request"></param>
        /// <returns></returns>
        public object CreateInstance(IFactoryRequest request)
        {
            var validationRulesType =
                typeof (ValidationRules<>).MakeGenericType(request.ServiceType.GetGenericArguments());
            if (!_ruleSets.ContainsKey(validationRulesType))
            {
                _ruleSets.Add(validationRulesType,Activator.CreateInstance(validationRulesType));    
            }

            return _ruleSets[validationRulesType];
        }
    }
}
